package com.pet.serve.service;

import com.pet.serve.entity.Pets;
import com.pet.serve.repository.PetsRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class PetsService {

    private final PetsRepository petsRepository;

    public PetsService(PetsRepository petsRepository) {
        this.petsRepository = petsRepository;
    }

    // 根据宠物的状态（售出、在售、寄养、领回）查找宠物
    public List<Pets> findByStatus(Pets.PetStatus status) {
        return petsRepository.findByStatus(status);
    }

    // 根据宠物的价格范围查找宠物
    public List<Pets> findByPriceRange(BigDecimal minPrice, BigDecimal maxPrice) {
        return petsRepository.findByPriceBetween(minPrice, maxPrice);
    }

    // 根据宠物ID查找宠物
    public Pets findByPetid(Long petid) {
        return petsRepository.findByPetid(petid);
    }

    // 根据宠物名字模糊查询
    public List<Pets> findByNameLike(String name) {
        return petsRepository.findByNameLike(name);
    }

    // 根据多个条件查询宠物（种类、状态、价格区间）
    public List<Pets> findPetsByConditions(String type, String status, Double minPrice, Double maxPrice) {
        return petsRepository.findPetsByConditions(type, status, minPrice, maxPrice);
    }

    // 分页查询宠物
    public List<Pets> findPetsWithPagination(int pageNo, int pageSize) {
        int offset = (pageNo - 1) * pageSize;
        return petsRepository.findPetsWithPagination(offset, pageSize);
    }

    public List<Pets> getAllPets() {
        return petsRepository.findAll();
    }

    // 根据状态和价格区间进行分页查询
    public Page<Pets> findPetsByConditionsWithPagination(Pets.PetStatus status, BigDecimal minPrice, BigDecimal maxPrice,String name,Pets.PetType petType, int pageNo, int pageSize) {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.by("createtime").descending());
        return petsRepository.findPetsByConditionsWithPagination(status, minPrice, maxPrice, name,petType,pageable);
    }

    public Page<Pets> findByType(Pets.PetType petType, Pageable pageable) {
        return petsRepository.findByType(petType, pageable);
    }

    public boolean deletePetByPetid(Long petid) {
        Pets pet = petsRepository.findByPetid(petid);
        if (pet == null) {
            return false;
        }
        petsRepository.delete(pet);
        return true;
    }
}
